/*
 * @Description: ------------ fileDescription -----------
 * @Author: snows_l snows_l@163.com
 * @Date: 2025-01-13 10:39:55
 * @LastEditors: snows_l snows_l@163.com
 * @LastEditTime: 2025-01-13 12:08:49
 * @FilePath: \Backstage\Server\src\router\donate.js
 */
const express = require('express');
const { verifyToken } = require('../utils/handleToken');
const { handleError } = require('../utils/common.js');
// 数据库操作
const db = require('../utils/connDB');
const moment = require('moment');

// 工具函数
const router = express.Router();

// 捐赠列表
router.get('/list', (req, res) => {
  const { page, size, name, startTime, endTime } = req.query;
  const offset = (page - 1) * size;
  const sql = `SELECT * FROM donate WHERE 1=1${name ? ` AND name LIKE '%${name}%'` : ''} ${
    startTime && endTime ? ` AND createTime between '${startTime}' and '${endTime}'` : ''
  } ORDER BY createTime DESC LIMIT ${size} OFFSET ${offset}`;

  const lenSql = `SELECT COUNT(*) as total FROM donate WHERE 1=1${name ? ` AND name LIKE '%${name}%'` : ''} ${
    startTime && endTime ? ` AND createTime between '${startTime}' and '${endTime}'` : ''
  }`;

  db.queryAsync(lenSql, [])
    .then(lenRes => {
      const total = lenRes.results[0].total;
      db.queryAsync(sql, [])
        .then(resData => {
          res.send({
            code: 200,
            data: resData.results,
            total,
            page,
            size
          });
        })
        .catch(err => {
          handleError(res, err);
        });
    })
    .catch(err => {
      handleError(res, err);
    });
});

// 新增捐赠
router.post('/add', (req, res) => {
  let token = req.cookies['bs-cookie'];
  try {
    const user = verifyToken(token);
    if (!user) throw new Error('JsonWebTokenError:token验证失败');
    if (user.role_key !== 'admin') throw new Error('ROLE_ERROR:权限不足');
    const { name, url, profile, avatar, money } = req.body;

    const sql = `INSERT INTO donate (name, url, profile, avatar, money, createTime) VALUES (?,?,?,?,?,?)`;
    const params = [name, url, profile, avatar, money, moment().format('YYYY-MM-DD HH:mm:ss')];
    db.queryAsync(sql, params)
      .then(resData => {
        res.send({
          code: 200,
          message: '新增成功'
        });
      })
      .catch(err => {
        handleError(res, err);
      });
  } catch (error) {
    handleError(res, error);
  }
});

// 修改捐赠
router.put('/update', (req, res) => {
  let token = req.cookies['bs-cookie'];
  try {
    const user = verifyToken(token);
    if (!user) throw new Error('JsonWebTokenError:token验证失败');
    if (user.role_key !== 'admin') throw new Error('ROLE_ERROR:权限不足');
    const { id, name, url, profile, avatar, money } = req.body;

    const sql = `UPDATE donate SET name =?, url =?, profile =?, avatar =?, money = ?, updateTime = ? WHERE id = ?`;
    const params = [name, url, profile, avatar, money, moment().format('YYYY-MM-DD HH:mm:ss'), id];
    db.queryAsync(sql, params)
      .then(resData => {
        res.send({
          code: 200,
          message: '修改成功'
        });
      })
      .catch(err => {
        handleError(res, err);
      });
  } catch (error) {
    handleError(res, error);
  }
});

// 删除捐赠
router.delete('/delete/:id', (req, res) => {
  let token = req.cookies['bs-cookie'];
  try {
    const user = verifyToken(token);
    if (!user) throw new Error('JsonWebTokenError:token验证失败');
    if (user.role_key !== 'admin') throw new Error('ROLE_ERROR:权限不足');
    const { id } = req.params;

    const sql = `DELETE FROM donate WHERE id = ?`;
    const params = [id];
    db.queryAsync(sql, params)
      .then(resData => {
        res.send({
          code: 200,
          message: '删除成功'
        });
      })
      .catch(err => {
        handleError(res, err);
      });
  } catch (error) {
    handleError(res, error);
  }
});

module.exports = router;
